from fastapi import APIRouter, HTTPException
from django.db import connection
from typing import List, Dict

router = APIRouter()

@router.get("/{warehouse_id}", response_model=List[Dict])
async def get_inventory(warehouse_id: int):
    """
    查询指定仓库的库存清单
    - 使用原生SQL查询提高性能
    - 返回格式: [{仓库ID, 物料ID, 数量, 状态}]
    - 异常处理：捕获数据库错误并返回500状态码
    """
    try:
        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT * FROM warehouse_inventory WHERE warehouse_id = %s",
                [warehouse_id]
            )
            # 将结果转换为字典列表
            columns = [col[0] for col in cursor.description]
            return [
                dict(zip(columns, row))
                for row in cursor.fetchall()
            ]
    except Exception as e:
        raise HTTPException(
            status_code=500, 
            detail=f"数据库错误: {str(e)}"
        )